import cv2
import numpy as np
import matplotlib.pyplot as plt

# 读取图像并转换为灰度图像
image_path = '2.webp'
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if image is None:
    print("Error: Unable to load image.")
    exit()

# 获取图像的高度和宽度
height, width = image.shape

# 初始化比特平面图像数组
bit_planes = np.zeros((8, height, width), dtype=np.uint8)

# 对每个像素进行比特平面分层
for i in range(8):
    bit_plane = 2 ** i  # 当前比特平面的掩码
    bit_planes[i] = cv2.bitwise_and(image, bit_plane)  # 提取当前比特平面

# 显示原始图像和每个比特平面
plt.figure(figsize=(12, 8))
plt.subplot(3, 3, 1)
plt.title('Original Image')
plt.imshow(image, cmap='gray')
plt.axis('off')

for i in range(8):
    plt.subplot(3, 3, i + 2)
    plt.title(f'Bit Plane {i + 1}')
    plt.imshow(bit_planes[i], cmap='gray')
    plt.axis('off')

plt.tight_layout()
plt.show()